
import 'package:elevator/db/error_data.dart';
import 'package:elevator/db/warning.dart';
import 'package:elevator/utils/utils_logger.dart';
import 'package:mysql1/mysql1.dart';

class DBHelper {
  // 单例模式
  static DBHelper? _instance;
  factory DBHelper() => _instance ??= DBHelper._internal();
  late MySqlConnection _conn;


  DBHelper._internal();

  void initDb() async {
    _conn =  await MySqlConnection.connect(ConnectionSettings(
        host: '36.141.45.30',
        port: 43306,
        user: 'root',
        password: 'adminemqx123',
        db: 'liftdb_base',
        useCompression: false,
        timeout:const Duration(seconds: 60),
        maxPacketSize:16 * 1024 * 1024 *1024,
        characterSet: CharacterSet.UTF8MB4));
  }

  // close mysql.ConnectionSettings
  void close() {
    _conn.close();
  }

  /// 查询tbapplwarncfg
  Future<List<Warning>> queryTbAppLWarnCfg() async {
    var result = await _conn.query('SELECT * FROM tbapplwarncfg');
    var lis = result.map((e) => Warning.fromJson(e.fields)).toList();
    return lis;
  }

  /// 查询error错误信息
  Future<List<ErrorData>> queryTpcErr({String tabName = 'tbtpcerrcode', DateTime? whichDay}) async {

    whichDay ??= DateTime.now();
    logd('queryTpcErr $whichDay');
    final dateString = '${whichDay.year}-${whichDay.month.toString().padLeft(2, '0')}-${whichDay.day.toString().padLeft(2, '0')}';
    var result = await _conn.query('SELECT * FROM $tabName WHERE DATE(fDateTime) = ?', [dateString]);

    var list = result.map((e) => ErrorData.fromJson(e.fields)).toList();

    logd('queryTpcErr result $list');
    return list;
  }

  /// 查询error错误信息
  Future<List<ErrorData>> queryTpcErrByPeriodTime({String tabName = 'tbtpcerrcode', required DateTime startTime, required DateTime endTime}) async {

    logd('queryTpcErr $startTime  $endTime');
    final startTimeStr = '${startTime.year}-${startTime.month.toString().padLeft(2, '0')}-${startTime.day.toString().padLeft(2, '0')}';
    final endTimeStr = '${endTime.year}-${endTime.month.toString().padLeft(2, '0')}-${endTime.day.toString().padLeft(2, '0')}';
    var result = await _conn.query('SELECT * FROM $tabName WHERE DATE(created_at) BETWEEN \'$startTimeStr\' AND \'$endTimeStr\';');

    var list = result.map((e) => ErrorData.fromJson(e.fields)).toList();

    logd('queryTpcErr result $list');
    return list;
  }

}